In [1]:
import numpy as np
print ("Loading package(s)")


Loading package(s)

In [2]:
print ("Hello, world")

# THERE ARE THREE POPULAR TYPES
# 1. INTEGER
x = 3;
print ("Integer: %01d, %02d, %03d, %04d, %05d" 
       % (x, x, x, x, x))
# 2. FLOAT
x = 123.456;
print ("Float: %.0f, %.1f, %.2f, %1.2f, %2.2f" 
       % (x, x, x, x, x))
# 3. STRING
x = "Hello, world"
print ("String: [%s], [%3s], [%20s]" 
       % (x, x, x))


Hello, world
Integer: 3, 03, 003, 0003, 00003
Float: 123, 123.5, 123.46, 123.46, 123.46
String: [Hello, world], [Hello, world], [        Hello, world]

In [3]:
dlmethods = ["ANN", "MLP", "CNN", "RNN", "DAE"]

for alg in dlmethods:
    if alg in ["ANN", "MLP"]:
        print ("We have seen %s" % (alg))


We have seen ANN
We have seen MLP

In [4]:
dlmethods = ["ANN", "MLP", "CNN", "RNN", "DAE"];
for alg in dlmethods:
    if alg in ["ANN", "MLP", "CNN"]:
        print ("%s is a feed-forward network." % (alg))
    elif alg in ["RNN"]:
        print ("%s is a recurrent network." % (alg))
    else:
        print ("%s is an unsupervised method." % (alg))


ANN is a feed-forward network.
MLP is a feed-forward network.
CNN is a feed-forward network.
RNN is a recurrent network.
DAE is an unsupervised method.

In [5]:
# Function definition looks like this
def sum(a, b):
    return a+b
X = 10.
Y = 20.
# Usage 
print ("%.1f + %.1f = %.1f" % (X, Y, sum(X, Y)))


10.0 + 20.0 = 30.0

In [6]:
head = "Deep learning" 
body = "very "
tail = "HARD."
print (head + " is " + body + tail)

# Repeat words
print (head + " is " + body*3 + tail)
print (head + " is " + body*10 + tail)

# It is used in this way
print ("\n" + "="*50)
print (" "*15 + "It is used in this way")
print ("="*50 + "\n")

# Indexing characters in the string
x = "Hello, world" 
for i in range(len(x)):
    print ("Index: [%02d/%02d] Char: %s" 
           % (i, len(x), x[i]))


Deep learning is very HARD.
Deep learning is very very very HARD.
Deep learning is very very very very very very very very very very HARD.

==================================================
               It is used in this way
==================================================

Index: [00/12] Char: H
Index: [01/12] Char: e
Index: [02/12] Char: l
Index: [03/12] Char: l
Index: [04/12] Char: o
Index: [05/12] Char: ,
Index: [06/12] Char:  
Index: [07/12] Char: w
Index: [08/12] Char: o
Index: [09/12] Char: r
Index: [10/12] Char: l
Index: [11/12] Char: d

In [8]:
# More indexing 
print ("")
idx = -2
print ("(%d)th char is %s" % (idx, x[idx]))
idxfr = 0
idxto = 8
print ("String from %d to %d is [%s]" 
       % (idxfr, idxto, x[idxfr:idxto]))
idxfr = 4
print ("String from %d to END is [%s]" 
       % (idxfr, x[idxfr:]))
x = "20160607Cloudy"
year = x[:4]
day = x[4:8]
weather = x[8:]
print ("[%s] -> [%s] + [%s] + [%s] " 
       % (x, year, day, weather))


(-2)th char is l
String from 0 to 8 is [Hello, w]
String from 4 to END is [o, world]
[20160607Cloudy] -> [2016] + [0607] + [Cloudy] 

In [10]:
a = []
b = [1, 2, 3]
c = ["Hello", ",", "world"]
d = [1, 2, 3, "x", "y", "z"]
x = []
print (x)
x.append('a')
print (x)
x.append(123)
print (x)
x.append(["a", "b"])
print (x)
print ("Length of x is %d " 
       % (len(x)))
for i in range(len(x)):
    print ("[%02d/%02d] %s" 
           % (i, len(x), x[i]))


[]
['a']
['a', 123]
['a', 123, ['a', 'b']]
Length of x is 3 
[00/03] a
[01/03] 123
[02/03] ['a', 'b']

In [11]:
z = []
z.append(1)
z.append(2)
z.append(3)
z.append('Hello')
for i in range(len(z)):
    print (z[i])


1
2
3
Hello

In [1]:
dic = dict()
dic["name"] = "Antonio"
dic["age"] = 43
dic["job"] = "Software Engineer"

print (dic)


{'job': 'Software Engineer', 'name': 'Antonio', 'age': 43}

In [14]:
class Greeter:

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print ('HELLO, %s!' 
                   % self.name.upper())
        else:
            print ('Hello, %s' 
                   % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"


Hello, Fred
HELLO, FRED!

In [15]:
def print_np(x):
    print ("Type is %s" % (type(x)))
    print ("Shape is %s" % (x.shape,))
    print ("Values are: \n%s" % (x))
    print

In [16]:
x = np.array([1, 2, 3]) # rank 1 array
print_np(x)

x[0] = 5
print_np(x)


Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[1 2 3]
Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[5 2 3]

In [17]:
y = np.array([[1,2,3], [4,5,6]]) 
print_np(y)


Type is <class 'numpy.ndarray'>
Shape is (2, 3)
Values are: 
[[1 2 3]
 [4 5 6]]

In [18]:
a = np.zeros((3, 2))  
print_np(a)


Type is <class 'numpy.ndarray'>
Shape is (3, 2)
Values are: 
[[ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]]

In [19]:
b = np.ones((1, 2))   
print_np(b)


Type is <class 'numpy.ndarray'>
Shape is (1, 2)
Values are: 
[[ 1.  1.]]

In [20]:
c = np.eye(2, 2)   
print_np(c)


Type is <class 'numpy.ndarray'>
Shape is (2, 2)
Values are: 
[[ 1.  0.]
 [ 0.  1.]]

In [21]:
d = np.random.random((2, 2))    
print_np(d)


Type is <class 'numpy.ndarray'>
Shape is (2, 2)
Values are: 
[[ 0.1946807   0.15497216]
 [ 0.58723898  0.16583897]]

In [22]:
e = np.random.randn(1, 10)    
print_np(e)


Type is <class 'numpy.ndarray'>
Shape is (1, 10)
Values are: 
[[-0.88089409  1.77647708 -0.59681193 -2.09430761 -0.00245805 -1.28253932
  -1.25116176 -0.37738168  0.27690442  0.82254266]]

In [23]:
# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print_np(a)

print
# Use slicing to pull out the subarray consisting 
# of the first 2 rows
# and columns 1 and 2; b is the following array 
# of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]
print_np(b)


Type is <class 'numpy.ndarray'>
Shape is (3, 4)
Values are: 
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
Type is <class 'numpy.ndarray'>
Shape is (2, 2)
Values are: 
[[2 3]
 [6 7]]

In [24]:
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print_np(a)

row_r1 = a[1, :]    # Rank 1 view of the second row of a  
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
row_r3 = a[[1], :]  # Rank 2 view of the second row of a

print_np(row_r1)
print_np(row_r2)
print_np(row_r3)


Type is <class 'numpy.ndarray'>
Shape is (3, 4)
Values are: 
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
Type is <class 'numpy.ndarray'>
Shape is (4,)
Values are: 
[5 6 7 8]
Type is <class 'numpy.ndarray'>
Shape is (1, 4)
Values are: 
[[5 6 7 8]]
Type is <class 'numpy.ndarray'>
Shape is (1, 4)
Values are: 
[[5 6 7 8]]

In [25]:
a = np.array([[1,2], [3, 4], [5, 6]])
print_np(a)

# An example of integer array indexing.
# The returned array will have shape (3,) and 
b = a[[0, 1, 2], [0, 1, 0]]
print_np(b)

# The above example of integer array indexing 
# is equivalent to this:
c = np.array([a[0, 0], a[1, 1], a[2, 0]])
print_np(c)


Type is <class 'numpy.ndarray'>
Shape is (3, 2)
Values are: 
[[1 2]
 [3 4]
 [5 6]]
Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[1 4 5]
Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[1 4 5]

In [26]:
x = np.array([1, 2])  # Let numpy choose the datatype
y = np.array([1.0, 2.0])  # Let numpy choose the datatype
z = np.array([1, 2], dtype=np.int64)  # particular datatype

print_np(x)
print_np(y)
print_np(z)


Type is <class 'numpy.ndarray'>
Shape is (2,)
Values are: 
[1 2]
Type is <class 'numpy.ndarray'>
Shape is (2,)
Values are: 
[ 1.  2.]
Type is <class 'numpy.ndarray'>
Shape is (2,)
Values are: 
[1 2]

In [29]:
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum; both produce the array
print (x + y)
print (np.add(x, y))


[[  6.   8.]
 [ 10.  12.]]
[[  6.   8.]
 [ 10.  12.]]

In [31]:
#  Elementwise difference; both produce the array
print (x - y)
print (np.subtract(x, y))


[[-4. -4.]
 [-4. -4.]]
[[-4. -4.]
 [-4. -4.]]

In [32]:
# Elementwise product; both produce the array
print (x * y)
print (np.multiply(x, y))


[[  5.  12.]
 [ 21.  32.]]
[[  5.  12.]
 [ 21.  32.]]

In [34]:
# Elementwise division; both produce the array
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]
print (x / y)
print (np.divide(x, y))


[[ 0.2         0.33333333]
 [ 0.42857143  0.5       ]]
[[ 0.2         0.33333333]
 [ 0.42857143  0.5       ]]

In [35]:
# Elementwise square root; produces the array
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]
print (np.sqrt(x))


[[ 1.          1.41421356]
 [ 1.73205081  2.        ]]

In [39]:
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])

print_np(x)
print_np(y)
print_np(v)
print_np(w)

# Inner product of vectors; both produce 219
print (v.dot(w))
print (np.dot(v, w)) # <= v * w'
# Matrix / vector product; both produce the rank 1 array [29 67]
print (x.dot(v))
print (np.dot(x, v)) # <= x * v'
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
#  [43 50]]
print (x.dot(y))
print (np.dot(x, y))


Type is <class 'numpy.ndarray'>
Shape is (2, 2)
Values are: 
[[1 2]
 [3 4]]
Type is <class 'numpy.ndarray'>
Shape is (2, 2)
Values are: 
[[5 6]
 [7 8]]
Type is <class 'numpy.ndarray'>
Shape is (2,)
Values are: 
[ 9 10]
Type is <class 'numpy.ndarray'>
Shape is (2,)
Values are: 
[11 12]
219
219
[29 67]
[29 67]
[[19 22]
 [43 50]]
[[19 22]
 [43 50]]

In [41]:
x = np.array([[1,2],[3,4]])
print_np(x)
print
print (x)
print (x.T)
print (np.sum(x))  # Compute sum of all elements
print (np.sum(x, axis=0))  # Compute sum of each column
print (np.sum(x, axis=1))  # Compute sum of each row


Type is <class 'numpy.ndarray'>
Shape is (2, 2)
Values are: 
[[1 2]
 [3 4]]
[[1 2]
 [3 4]]
[[1 3]
 [2 4]]
10
[4 6]
[3 7]

In [43]:
print (x)
print (x.T)


[[1 2]
 [3 4]]
[[1 3]
 [2 4]]

In [44]:
v = np.array([1,2,3])
print (v)
print (v.T)


[1 2 3]
[1 2 3]

In [45]:
v = np.array([[1,2,3]])
print (v)
print (v.T)


[[1 2 3]]
[[1]
 [2]
 [3]]

In [46]:
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)    # Create an empty matrix 
                        # with the same shape as x

print_np(x)
print_np(v)
print_np(y)


Type is <class 'numpy.ndarray'>
Shape is (4, 3)
Values are: 
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[1 0 1]
Type is <class 'numpy.ndarray'>
Shape is (4, 3)
Values are: 
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]

In [47]:
# Add the vector v to each row of the matrix x 
# with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v
print_np(y)


Type is <class 'numpy.ndarray'>
Shape is (4, 3)
Values are: 
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]

In [48]:
vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
print_np(vv)             # Prints "[[1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]]"


Type is <class 'numpy.ndarray'>
Shape is (4, 3)
Values are: 
[[1 0 1]
 [1 0 1]
 [1 0 1]
 [1 0 1]]

In [49]:
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using BROADCASTING
print_np(x)
print_np(v)
print_np(y)


Type is <class 'numpy.ndarray'>
Shape is (4, 3)
Values are: 
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[1 0 1]
Type is <class 'numpy.ndarray'>
Shape is (4, 3)
Values are: 
[[ 2  2  4]
 [ 5  5  7]
 [ 8  8 10]
 [11 11 13]]

In [51]:
# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])

print_np(x)
print_np(v)
print (x + v)


Type is <class 'numpy.ndarray'>
Shape is (2, 3)
Values are: 
[[1 2 3]
 [4 5 6]]
Type is <class 'numpy.ndarray'>
Shape is (3,)
Values are: 
[1 0 1]
[[2 2 4]
 [5 5 7]]

In [54]:
# Add a vector to each column of a matrix
print_np(x)
print_np(w)
print ((x.T + w).T)

# Another solution is to reshape w 
# to be a row vector of shape (2, 1);
print
print (x + np.reshape(w, (2, 1)))


Type is <class 'numpy.ndarray'>
Shape is (2, 3)
Values are: 
[[1 2 3]
 [4 5 6]]
Type is <class 'numpy.ndarray'>
Shape is (2,)
Values are: 
[11 12]
[[12 13 14]
 [16 17 18]]
[[12 13 14]
 [16 17 18]]

Matplotlib


In [55]:
import matplotlib.pyplot as plt
%matplotlib inline

In [56]:
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
lt.plot(x, y)


Out[56]:
[<matplotlib.lines.Line2D at 0x7f01d9140668>]

In [58]:
y_sin = np.sin(x)
y_cos = np.cos(x)
# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])

# Show the figure.
plt.show()



In [ ]: